package cc.rengu.oltp.service.common.dao.impl;

import cc.rengu.jradp.mods.xml.XmlTree;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.TxnCfgMapper;
import cc.rengu.oltp.service.common.entity.TxnCfg;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 交易配置信息表操作接口实现类
 * Created by wangc on 2020/5/8.
 */
public class TxnCfgMapperImpl implements TxnCfgMapper {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppParamConstant.OLTP_POOL_NAME);

    public TxnCfgMapperImpl() throws Exception {
        if (XmlTree.hasThreadTree()) {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
            if (null != corporation && !corporation.isEmpty()) {
                String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppParamConstant.OLTP_POOL_NAME);
            }
        }
    }

    @Override
    public int insertTxncfg(TxnCfg txnCfg) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "insertTxncfg");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, txnCfg, null);
        if (0 != iReturnCode) {
            rglog.error("登记交易配置信息失败,bizProdCode:<{}>,txnGroup:<{}>,txnNum:<{}>,iReturnCode:<{}>", txnCfg.getBizProdCode(), txnCfg.getTxnGroup(), txnCfg.getTxnNum(), iReturnCode);
        }
        return iReturnCode;
    }

    @Override
    public List<TxnCfg> selectTxnCfgByBizProdCode(String bizProdCode, String txnGroup) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectTxnCfgByBizProdCode");
        TxnCfg txnCfg = new TxnCfg();
        txnCfg.setBizProdCode(bizProdCode);
        if (!StringUtil.isEmptyOrNull(txnGroup)) {
            txnCfg.setTxnGroup(txnGroup);
        }
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, txnCfg, TxnCfg.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.warn("根据业务产品代码查询交易配置信息失败,bizProdCode:<{}>,txnGroup:<{}>", bizProdCode, txnGroup);
            return null;
        }
        return objectList.stream().map(item -> (TxnCfg) item).collect(Collectors.toList());
    }
}
